import React, { useState, useEffect } from 'react';
import {
  Box,
  TextField,
  Button,
  Typography,
  DialogTitle,
  DialogContent,
  DialogActions,
  IconButton,
  Grid,
  Alert,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Divider,
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import { Product, RateRecord, TimeLabel, NetWorthRecord } from '../../types/product';
import { saveProduct } from '../../services/storage';

// 格式化日期为输入框可用的格式 (YYYY-MM-DD)
const formatDateForInput = (date: Date): string => {
  if (!date) return '';
  const d = new Date(date);
  return d.toISOString().split('T')[0];
};

// 验证日期输入并返回有效的日期字符串
const validateDate = (dateStr: string): string => {
  if (!dateStr) return new Date().toISOString().split('T')[0];
  const date = new Date(dateStr);
  return isNaN(date.getTime()) 
    ? new Date().toISOString().split('T')[0] 
    : dateStr;
};

interface ProductFormProps {
  product?: Product | null;
  onClose: () => void;
  addingNetWorth?: boolean;
}

const ProductForm: React.FC<ProductFormProps> = ({ product, onClose, addingNetWorth }) => {
  const [formData, setFormData] = useState<Omit<Product, 'id' | 'createdAt' | 'updatedAt'>>({
    bank: '',
    name: '',
    netWorth: 1.0000,
    netWorthDate: new Date().toISOString().split('T')[0],
    netWorthHistory: [],
    investments: [],
    historyRates: [],
  });

  // 自动更新最新净值
  useEffect(() => {
    if (formData.netWorthHistory.length > 0) {
      // 按日期排序，获取最新的净值记录
      const sortedHistory = [...formData.netWorthHistory].sort((a, b) => 
        new Date(b.date).getTime() - new Date(a.date).getTime()
      );
      const latestRecord = sortedHistory[0];
      
      setFormData(prev => ({
        ...prev,
        netWorth: latestRecord.value,
        netWorthDate: latestRecord.date
      }));
    }
  }, [formData.netWorthHistory]);

  const [error, setError] = useState<string>('');

  useEffect(() => {
    if (product) {
      if (addingNetWorth) {
        // 添加净值模式：保留原有信息，但默认添加一条新的净值记录
        const newRecord: NetWorthRecord = {
          id: Date.now().toString(),
          date: new Date().toISOString().split('T')[0],
          value: product.netWorth, // 使用最新净值作为默认值
        };

        setFormData({
          ...product,
          netWorthHistory: [...product.netWorthHistory, newRecord],
        });
      } else {
        // 普通编辑模式：加载所有原有信息
        const { id, createdAt, updatedAt, ...rest } = product;
        setFormData(rest);
      }
    }
  }, [product, addingNetWorth]);

  const calculateDailyProfit = (annualRate: number): number => {
    return Number(((10000 * (annualRate / 100)) / 365).toFixed(2));
  };

  const addNetWorthRecord = () => {
    const newRecord: NetWorthRecord = {
      id: Date.now().toString(),
      date: new Date().toISOString().split('T')[0],
      value: formData.netWorth, // 使用当前净值作为默认值
    };

    setFormData(prev => ({
      ...prev,
      netWorthHistory: [...prev.netWorthHistory, newRecord],
    }));
  };

  const updateNetWorthRecord = (id: string, field: keyof NetWorthRecord, value: any) => {
    setFormData(prev => ({
      ...prev,
      netWorthHistory: prev.netWorthHistory.map(record =>
        record.id === id
          ? { ...record, [field]: value }
          : record
      ),
    }));
  };

  const removeNetWorthRecord = (id: string) => {
    setFormData(prev => ({
      ...prev,
      netWorthHistory: prev.netWorthHistory.filter(record => record.id !== id),
    }));
  };

  const addRateRecord = () => {
    const now = new Date();
    const nextMonth = new Date(now);
    nextMonth.setMonth(nextMonth.getMonth() + 1);
    
    const newRecord: RateRecord = {
      id: Date.now().toString(),
      startDate: now,
      endDate: nextMonth,
      rate: 0,
      advertisedRate: 0,
      dailyProfit: 0,
      timeLabel: TimeLabel.OneMonth,
    };

    setFormData(prev => ({
      ...prev,
      historyRates: [...prev.historyRates, newRecord],
    }));
  };

  const updateRateRecord = (index: number, field: keyof RateRecord, value: any) => {
    setFormData(prev => {
      const historyRates = [...prev.historyRates];
      const updatedRecord = {
        ...historyRates[index],
        [field]: field.includes('Date') ? (value ? new Date(value) : new Date()) : 
                field === 'timeLabel' ? value :
                Number(value),
      };

      if (field === 'advertisedRate') {
        updatedRecord.dailyProfit = calculateDailyProfit(Number(value));
      }

      historyRates[index] = updatedRecord;
      return { ...prev, historyRates };
    });
  };

  const removeRateRecord = (index: number) => {
    setFormData(prev => ({
      ...prev,
      historyRates: prev.historyRates.filter((_: RateRecord, i: number) => i !== index),
    }));
  };

  const handleSubmit = () => {
    if (!formData.bank || !formData.name) {
      setError('请填写所有必填字段');
      return;
    }

    // 验证净值记录
    for (const record of formData.netWorthHistory) {
      if (!record.date) {
        setError('请选择所有净值记录的日期');
        return;
      }
      if (record.value <= 0 || String(record.value).split('.')[1]?.length > 6) {
        setError('净值格式不正确（最多4位小数）');
        return;
      }
    }

    // 验证收益率记录
    for (const record of formData.historyRates) {
      if (record.startDate >= record.endDate) {
        setError('收益率记录的开始日期必须早于结束日期');
        return;
      }
      if (record.advertisedRate < 0) {
        setError('收益率不能为负数');
        return;
      }
    }

    const productData: Product = {
      ...formData,
      id: product?.id || Date.now().toString(),
      createdAt: product?.createdAt || new Date(),
      updatedAt: new Date(),
    };

    try {
      saveProduct(productData);
      onClose();
    } catch (err) {
      setError('保存失败，请重试');
    }
  };

  // 验证日期格式和范围
  const validateDate = (dateStr: string): string => {
    // 如果日期格式不正确，返回今天的日期
    if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
      return new Date().toISOString().split('T')[0];
    }

    const [year, month, day] = dateStr.split('-').map(Number);
    
    // 年份支持手动输
    const validYear = year;   

    // 限制月份范围在 1-12
    const validMonth = Math.min(Math.max(month, 1), 12);
    
    // 获取当月的最大天数
    const maxDays = new Date(validYear, validMonth, 0).getDate();
    // 限制日期范围在 1-当月最大天数
    const validDay = Math.min(Math.max(day, 1), maxDays);

    // 格式化为 YYYY-MM-DD
    return `${String(validYear).padStart(4, '0')}-${String(validMonth).padStart(2, '0')}-${String(validDay).padStart(2, '0')}`;
  };

  const formatDateForInput = (date: Date): string => {
    if (!(date instanceof Date) || isNaN(date.getTime())) {
      return new Date().toISOString().split('T')[0];
    }
    return validateDate(date.toISOString().split('T')[0]);
  };

  return (
    <>
      <DialogTitle>
        {addingNetWorth ? '添加净值记录' : (product ? '编辑理财产品' : '添加理财产品')}
      </DialogTitle>
      <DialogContent>
        <Box mt={2}>
          {error && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {error}
            </Alert>
          )}

          {!addingNetWorth && (
            <>
              <Grid container spacing={2}>
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="银行名称"
                    required
                    value={formData.bank}
                    onChange={(e) => setFormData(prev => ({ ...prev, bank: e.target.value }))}
                  />
                </Grid>
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="产品名称"
                    required
                    value={formData.name}
                    onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                  />
                </Grid>
              </Grid>
            </>
          )}

          {!addingNetWorth && (
            <>
              <Box mt={3}>
                <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
                  <Typography variant="subtitle1">产品业绩信息</Typography>
                  <Button
                    variant="outlined"
                    size="small"
                    onClick={addRateRecord}
                  >
                    添加业绩信息
                  </Button>
                </Box>
                
                {/* 添加表头 */}
                <Grid container spacing={2} sx={{ mb: 2, fontWeight: 'medium' }}>
                  <Grid item xs={12} sm={3}>
                    <Typography variant="body2">开始日期</Typography>
                  </Grid>
                  <Grid item xs={12} sm={3}>
                    <Typography variant="body2">结束日期</Typography>
                  </Grid>
                  <Grid item xs={12} sm={2}>
                    <Typography variant="body2">宣传年化率(%)</Typography>
                  </Grid>
                  <Grid item xs={12} sm={3}>
                    <Typography variant="body2">时间标签</Typography>
                  </Grid>
                  <Grid item xs={12} sm={1}>
                    <Typography variant="body2">万份收益</Typography>
                  </Grid>
                </Grid>

                {formData.historyRates?.map((rate, index) => (
                  <Box key={rate.id} mb={2}>
                    <Grid container spacing={2} alignItems="center">
                      <Grid item xs={12} sm={3}>
                        <TextField
                          fullWidth
                          type="date"
                          label="开始日期"
                          required
                          value={formatDateForInput(rate.startDate)}
                          onChange={(e) => updateRateRecord(index, 'startDate', new Date(validateDate(e.target.value)))}
                          InputLabelProps={{ shrink: true }}
                        />
                      </Grid>
                      <Grid item xs={12} sm={3}>
                        <TextField
                          fullWidth
                          type="date"
                          label="结束日期"
                          required
                          value={formatDateForInput(rate.endDate)}
                          onChange={(e) => updateRateRecord(index, 'endDate', new Date(validateDate(e.target.value)))}
                          InputLabelProps={{ shrink: true }}
                        />
                      </Grid>
                      <Grid item xs={12} sm={2}>
                        <TextField
                          fullWidth
                          type="number"
                          label="宣传年化率(%)"
                          required
                          inputProps={{ step: '0.01', min: '0' }}
                          value={rate.advertisedRate}
                          onChange={(e) => updateRateRecord(index, 'advertisedRate', e.target.value)}
                        />
                      </Grid>
                      <Grid item xs={12} sm={3}>
                        <FormControl fullWidth>
                          <InputLabel>时间标签</InputLabel>
                          <Select
                            value={rate.timeLabel}
                            label="时间标签"
                            onChange={(e) => updateRateRecord(index, 'timeLabel', e.target.value)}
                          >
                            {Object.values(TimeLabel).map((label) => (
                              <MenuItem key={label} value={label}>
                                {label}
                              </MenuItem>
                            ))}
                          </Select>
                        </FormControl>
                      </Grid>
                      <Grid item xs={12} sm={1}>
                        <Typography variant="body2" color="textSecondary">
                          {rate.dailyProfit.toFixed(2)}元
                        </Typography>
                      </Grid>
                      <Grid item xs={12} sm={1}>
                        <IconButton
                          color="error"
                          onClick={() => removeRateRecord(index)}
                        >
                          <DeleteIcon />
                        </IconButton>
                      </Grid>
                    </Grid>
                  </Box>
                ))}
              </Box>
              
              <Divider sx={{ my: 3 }} />
            </>
          )}

          <Box mt={3}>
            <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
              <Typography variant="subtitle1">历史净值记录</Typography>
              <Button
                variant="outlined"
                size="small"
                onClick={addNetWorthRecord}
              >
                添加净值记录
              </Button>
            </Box>

            {formData.netWorthHistory.map((record) => (
              <Box key={record.id} mb={2}>
                <Grid container spacing={2} alignItems="center">
                  <Grid item xs={12} sm={5}>
                    <TextField
                      fullWidth
                      type="date"
                      label="净值日期"
                      required
                      value={record.date}
                      onChange={(e) => updateNetWorthRecord(record.id, 'date', validateDate(e.target.value))}
                      InputLabelProps={{ shrink: true }}
                    />
                  </Grid>
                  <Grid item xs={12} sm={5}>
                    <TextField
                      fullWidth
                      type="number"
                      label="单位净值"
                      required
                      inputProps={{ step: '0.0001', min: '0' }}
                      value={record.value}
                      onChange={(e) => updateNetWorthRecord(record.id, 'value', Number(e.target.value))}
                    />
                  </Grid>
                  <Grid item xs={12} sm={2}>
                    <IconButton
                      color="error"
                      onClick={() => removeNetWorthRecord(record.id)}
                    >
                      <DeleteIcon />
                    </IconButton>
                  </Grid>
                </Grid>
              </Box>
            ))}
          </Box>
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>取消</Button>
        <Button
          variant="contained"
          onClick={handleSubmit}
        >
          保存
        </Button>
      </DialogActions>
    </>
  );
};

export default ProductForm;